﻿using System;

using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Core.Resource;

namespace Light.IoC
{
    /// <summary>
    /// 基于Castle的IoC组件工厂,用来创建业务组件实例
    /// </summary>
    public class CastleFactory : IFactory
    {
        private static IWindsorContainer container;

        public CastleFactory()
        {
            if (container == null)
            {
                lock (this)
                {
                    if (container == null)
                    {
                        container = new WindsorContainer(new XmlInterpreter(new ConfigResource()));
                    }
                }
            }
        }

        public T Create<T>()
        {
            if (container != null)
                return container.Resolve<T>();
            else
                return default(T);
        }

        public T Create<T>(string key)
        {
            if (container != null)
                return container.Resolve<T>(key);
            else
                return default(T);
        }

        public object Create(Type type)
        {
            if (container != null)
                return container.Resolve(type);
            else
                return null;
        }

        public void Dispose()
        {
            if (container != null)
                container.Dispose();
        }
    }
}
